/**
 * Created by 鄢鹏权 on 2017/04/08.
 */
///<reference path="Avalon.ts"/>
///<reference path="Config.ts"/>
///<reference path="Index.ts"/>

namespace Avalon{
    import Item = Menu.Item;
    export class Router{
        static routerMap:Object={};
        static error() {
            console.log('Router error');
            if(typeof Config.routerError === 'function'){
                Config.routerError();
            }
        }
        static loadVM(Obj,ID,Type,Dir:string='') {
            console.log(Dir,Obj,Type,ID)
            if(Config.routerMap[Obj]){
                this.load(Obj,ID,Type,Dir);
            }else{
                //循环添加到路由表中
                let doRouterMap = function(menu){
                    for (let item of menu){
                        if(!Config.routerMap[item.Obj]){
                            Config.routerMap[item.Obj]={}
                        }
                        if(item.Sub.length>0){
                            doRouterMap(item.Sub)
                        }
                        if(!Config.routerMap[item.Obj][item.Type]){
                            Config.routerMap[item.Obj][item.Type]=item
                        }
                    }
                };
                doRouterMap(Menu.Menu.menu);
                this.load(Obj,ID,Type,Dir);
            }
        }
        static load(Obj,ID,Type,Dir:string=''){
            if(Config.needAuth){
                if(groupAuth(index.user.Groups,Config.routerMap[Obj]&&Config.routerMap[Obj][Type]&&Config.routerMap[Obj][Type]['Group']?Config.routerMap[Obj][Type]['Group']:[])){

                }else{
                    Config.authFailed(Config.routerMap[Obj][Type]);
                    return false;
                }
            }
            index.nav=avalon.mix({},Config.routerMap[Obj][Type]);
            if(Config.routerMap[Obj]){
                let path:string='';
                let vmPath = Obj+'.js';
                if(Config.routerMap[Obj][Type]){
                    if(Config.routerMap[Obj][Type].Html) {
                        path=Config.routerMap[Obj][Type].Html;
                    }
                }
                if(path.length<1){
                    if(Type){
                        path = Obj+"_"+Type+'.html';
                    }else{
                        path = Obj+'.html';
                    }
                }
                if(path.slice(-5)!='.html'){
                    path+='.html'
                }
                if(Dir){
                    path=(Dir.slice(-1)=='/'?Dir:(Dir+'/'))+path;
                    vmPath=(Dir.slice(-1)=='/'?Dir:(Dir+'/'))+vmPath;
                }
                if(Config.debug){
                    path=path+'?v'+new Date().getTime();
                }
                let p = path.replace('_','/').substr(0,path.length-5);
                let o = p.split('/');
                let html = Config.getHTML(o[1], o[2], o[0]);
                if((avalon.vmodels[Obj]&&avalon.vmodels[Obj].SelfTPL[Type]==undefined) && html){
                    index.contentHtml=html;
                    if(typeof avalon.vmodels[Obj]['_after_'+Type] == "function")
                        avalon.vmodels[Obj]['_after_'+Type].apply(avalon.vmodels[Obj],[ID,Config.PageParams,Type])
                    Config.loadTplSuccess(Config.TPLDir+path);
                }else{
                    Castle.Request.getHtml(Config.TPLDir+path,function (html) {
                        Config.setHTML(Obj,Type,html,Dir);
                        if(avalon.vmodels[Obj]['SelfTPL'][Type]){
                            avalon.vmodels[Obj].html=html;
                        }else{
                            index.contentHtml=html;
                        }
                        if(typeof avalon.vmodels[Obj]['_after_'+Type] == "function")
                            avalon.vmodels[Obj]['_after_'+Type].apply(avalon.vmodels[Obj],[ID,Config.PageParams,Type])
                        Config.loadTplSuccess(Config.TPLDir+path);
                    },function (e) {
                        console.log(path+'模板加载失败')
                        Config.loadTplError(Config.TPLDir+path);
                    });
                }
                let vm = function () {
                    avalon.vmodels[Obj].Type=Type;
                    if(Config._initedVM.indexOf(Obj)==-1){
                        avalon.vmodels[Obj].init.apply(avalon.vmodels[Obj],[ID,Config.PageParams,Type])
                        Config._initedVM.push(Obj);
                    }
                    avalon.vmodels[Obj].ready.apply(avalon.vmodels[Obj],[ID,Config.PageParams,Type])
                    if(typeof avalon.vmodels[Obj]['ready_'+Type] == "function")
                        avalon.vmodels[Obj]['ready_'+Type].apply(avalon.vmodels[Obj],[ID,Config.PageParams,Type])
                }
                if(avalon.vmodels[Obj]){
                    vm()
                }else{
                    Castle.Request.getJs(Config.VMDir+vmPath,function () {
                        if(avalon.vmodels[Obj]){
                            vm()
                        }else{
                            Config.loadError(Obj,Type);
                        }
                    },function (err) {
                        
                    })
                }
            }else{
                Config.routerError();
                console.log('模块加载失败')
            }
        }
        static ready(){
            avalon.router.add('\/{Obj:[A-Z][a-z0-9]+}\/{id:int}',function (Obj,ID) {
                // console.log(Obj,ID)
                Avalon.Router.loadVM(Obj,ID,'');
            });
            avalon.router.add('\/{Obj:[A-Z][a-z0-9]+}\/{Type:[A-Z][a-z0-9]+}\/{id:int}',function (Obj,Type,ID) {
                // console.log(Obj,ID)
                Avalon.Router.loadVM(Obj,ID,Type);
            });
            avalon.router.add('\/{Obj:[A-Z][a-z0-9]+}_{Type:[A-Z][a-z0-9]+}\/{id:int}',function (Obj,Type,ID) {
                Avalon.Router.loadVM(Obj,ID,Type);
            });
            avalon.router.add('\/{Dir:[A-Z][a-z0-9]+}\/{Obj:[A-Z][a-z0-9]+}_{Type:[A-Z][a-z0-9]+}\/{id:int}',function (Dir,Obj,Type,ID) {
                Avalon.Router.loadVM(Obj,ID,Type,Dir);
            });
            avalon.router.error(this.error)
            avalon.history.start({
                root: "/"
            })
        }
    }
}